from flask_restplus import Resource, Namespace, fields, marshal
from common.decorators import catch_error
from common.responses import ok
from common import constant
from common.response_model import base_model
from common.request_parser import get_parser as base_get_parser
from app.user.decorators import token_required
from app.operation_log.model import OperationLog
from app.operation_log import dao
from app.user.controller import simple_user_model
from app.user.decorators import permission_required, permission_can, check_permission
from app.user.role_service import PermissionKey
api = Namespace('operation_log')

# ---------- model ----------
operation_log_model = base_model.inherit('operation_log_model', {
    "operation_log_type": fields.String(description='计提类型'),
    'parent_id': fields.Integer(),
    "action_str": fields.String(description='操作类型'),
    'creator': fields.Nested(simple_user_model),
    'updater': fields.Nested(simple_user_model),

})

# ---------- get parser ----------
get_parser = base_get_parser.copy()
get_parser.replace_argument('sorted_by', type=str, choices=[
    'name', 'id'
], default='id', help='sorted_by')
get_parser.add_argument('operation_log_type', type=str, help='类型', choices=constant.OperationLogType.ALL + [None])
get_parser.add_argument('parent_id', type=int, help='parent_id')
get_parser.add_argument('action_str', type=str, help='操作类型', choices=constant.OperationAction.ALL + [None])
get_parser.add_argument('date_begin', type=str, help='开始日期')
get_parser.add_argument('date_end', type=str, help='结束日期')
get_parser.add_argument('creator_id', type=str, help='创建人')


class OperationLogsResource(Resource):
    @catch_error
    @token_required
    @api.expect(get_parser)
    @permission_required(PermissionKey.OPERATION_LOG_GET)
    def get(self):
        """获取列表"""
        args = get_parser.parse_args()

        if args.get('parent_id') is None:
            check_permission(PermissionKey.OPERATION_LOG_GET_ALL)

        pagination = dao.get_by_page(**args)
        # 重新根据id获取
        new_items = []
        for item in pagination['items']:
            operation_log = OperationLog.query.filter_by(id=item['id']).first()
            new_items.append(marshal(operation_log, operation_log_model))
        pagination['items'] = new_items
        return ok(data=pagination,
                  message='get success')


# --------- route ----------
api.add_resource(OperationLogsResource, '/operation_logs')

# 注册 response 文档
api.models[operation_log_model.name] = operation_log_model
